package com.datasource.datasourceslink;

import com.datasource.datasourceslink.dao.test1.TestDao1;
import com.datasource.datasourceslink.dao.test2.TestDao2;
import org.apache.tomcat.jni.Time;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;

@Component
public class DataMigration {

    @Autowired
    TestDao1 testDao1;
    @Autowired
    TestDao2 testDao2;

    @PostConstruct//项目启动后自动开始运行一次
    public void init(){
        System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
        for (int i = 0; i > -1; i++) {
        // 取出数据库1的数据
        System.out.println("获取数据中");
        List<Map<String, Object>> maps = testDao2.selectAll();
        System.out.println("获取结束，正在分发数据");
        //循环插入到数据库2里
        for (Map<String, Object> map : maps) {
            try {
                //查询有无此数据
                Integer count = testDao1.selectOne((Integer) map.get("id"));
                if (count==1) {
                    testDao1.delete((Integer) map.get("id"));
                    testDao1.addOne(map);
                }
                else{
                    testDao1.addOne(map);
                }
                System.out.println(map);
                System.out.println("分发成功"+map.get("id"));
            }catch (Exception e){
                System.out.println("分发失败"+map.get("id"));
                System.out.println(e.getMessage());
            }
        }

        System.out.println("数据迁移结束");
        System.out.println("重新获取数据");
            for (int j = 10; j >0; j--) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(j);
            }
        }
    }
}
